<template>
  <div class="app-container">
    <!-- 面包屑 -->
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/trainingManagement' }">培养方案管理</el-breadcrumb-item>
        <el-breadcrumb-item>
          {{ isAuditMode ? '审核培养方案' : (isEditMode ? '修改培养方案' : '新增培养方案') }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 第一行：学科及方向（左，md:6） + 信息管理（右，md:18） -->
    <el-row :gutter="20" class="mt-4">
      <!-- 左侧：学科及方向设置 -->
      <el-col :md="6">
        <el-card>
          <div class="section-title">
            <h3>适用培养方案学科及方向设置</h3>
          </div>
          <el-form ref="disciplineFormRef" :model="stateForm" :rules="crules" label-width="100px" class="uniform-form">
            <!-- 1. 所属学院 -->
            <el-row :gutter="16" class="mb-4 uniform-row">
              <el-col :xs="24">
                <el-form-item label="所属学院" prop="collegeId" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.collegeId"
                      placeholder="请输入学院名称/代码"
                      clearable
                      filterable
                      remote
                      :remote-method="filterColleges"
                      :loading="collegeLoading"
                      style="width: 100%"
                      @change="handleCollegeChange"
                      :disabled="isEditMode || isAuditMode"
                  >
                    <el-option
                        v-for="college in filteredColleges"
                        :key="college.collegeId"
                        :label="`${college.collegeName} (${college.collegeCode})`"
                        :value="college.collegeId"
                    >
                      <span style="float: left">{{ college.collegeName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ college.collegeCode }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 2. 招生类型按钮 -->
            <el-row :gutter="16" class="mb-4 uniform-row">
              <el-col :xs="24">
                <div class="uniform-button-container">
                  <el-form-item class="uniform-button-form-item">
                    <div class="discipline-buttons">
                      <el-button
                          type="primary"
                          :class="{ 'is-active': admissionType === 'firstLevel' }"
                          @click="setAdmissionType('firstLevel')"
                          :disabled="isEditMode || isAuditMode"
                      >
                        一级学科招生
                      </el-button>
                      <el-button
                          type="primary"
                          :class="{ 'is-active': admissionType === 'secondLevel' }"
                          @click="setAdmissionType('secondLevel')"
                          :disabled="isEditMode || isAuditMode"
                          class="ml-4"
                      >
                        二级学科招生
                      </el-button>
                    </div>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <!-- 3. 学科选择框 -->
            <el-row :gutter="16" class="uniform-row">
              <el-col :xs="24" v-if="admissionType === 'firstLevel'">
                <!-- 一级学科行 -->
                <el-form-item label="一级学科" prop="firstLevelDiscipline" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.firstLevelDiscipline"
                      placeholder="请选择一级学科"
                      style="width: 100%"
                      @change="handleFirstLevelChange"
                      :disabled="isEditMode || isAuditMode"
                  >
                    <el-option
                        v-for="discipline in firstLevelDisciplines"
                        :key="discipline.id"
                        :label="`${discipline.firstSubjectName} (${discipline.firstSubjectCode})`"
                        :value="discipline.id"
                    />
                  </el-select>
                </el-form-item>
                <!-- 学科方向行 -->
                <el-form-item label="学科方向" prop="disciplineDirection" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.disciplineDirection"
                      placeholder="请选择学科方向"
                      style="width: 100%"
                      :disabled="!availableDirections.length || isEditMode || isAuditMode"
                      multiple
                  >
                    <el-option
                        v-for="direction in availableDirections"
                        :key="direction.id"
                        :label="direction.name"
                        :value="direction.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" v-else>
                <!-- 一级学科行 -->
                <el-form-item label="一级学科" prop="firstLevelDiscipline" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.firstLevelDiscipline"
                      placeholder="请选择一级学科"
                      style="width: 100%"
                      @change="handleFirstLevelChange"
                      :disabled="isEditMode || isAuditMode"
                  >
                    <el-option
                        v-for="discipline in firstLevelDisciplines"
                        :key="discipline.id"
                        :label="`${discipline.firstSubjectName} (${discipline.firstSubjectCode})`"
                        :value="discipline.id"
                    />
                  </el-select>
                </el-form-item>
                <!-- 二级学科行 -->
                <el-form-item label="二级学科" prop="secondLevelDiscipline" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.secondLevelDiscipline"
                      placeholder="请选择二级学科"
                      style="width: 100%"
                      :disabled="!availableSecondLevels.length || isEditMode || isAuditMode"
                      @change="handleSecondLevelChange"
                  >
                    <el-option
                        v-for="discipline in availableSecondLevels"
                        :key="discipline.id"
                        :label="discipline.secondSubjectName"
                        :value="discipline.id"
                    />
                  </el-select>
                </el-form-item>
                <!-- 研究方向行 -->
                <el-form-item label="研究方向" prop="disciplineDirection" class="uniform-form-item">
                  <el-select
                      v-model="stateForm.disciplineDirection"
                      placeholder="请选择研究方向"
                      style="width: 100%"
                      :disabled="!availableDirections.length || isEditMode || isAuditMode"
                      multiple
                  >
                    <el-option
                        v-for="direction in availableDirections"
                        :key="direction.id"
                        :label="direction.name"
                        :value="direction.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：培养方案信息管理 -->
      <el-col :md="18">
        <el-card>
          <div class="section-title">
            <h3>培养方案信息管理</h3>
          </div>
          <div class="program-section">
            <el-form ref="creditFormRef" :model="stateForm" :rules="crules" label-width="120px">
              <!-- 第一部分：基础信息 -->
              <div class="form-section">
                <h4 class="section-subtitle">基础信息</h4>
                <el-row :gutter="24" class="form-grid mb-6">
                  <!-- 第一行：方案编号、方案名称、英文名称 -->
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="方案编号" prop="programCode" class="narrow-input-item">
                      <el-input v-model="stateForm.programCode" placeholder="请输入" :disabled="isAuditMode" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="方案名称" prop="name" class="narrow-input-item">
                      <el-input v-model="stateForm.name" placeholder="请输入" :disabled="isAuditMode" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="英文名称" prop="englishName" class="narrow-input-item">
                      <el-input v-model="stateForm.englishName" placeholder="请输入" :disabled="isAuditMode" />
                    </el-form-item>
                  </el-col>

                  <!-- 第二行：年级、培养方案类型、限制条件 -->
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="年级" prop="grade" class="narrow-input-item">
                      <el-select v-model="stateForm.grade" placeholder="请选择" style="width: 100%" :disabled="isAuditMode">
                        <el-option v-for="dict in grade" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="培养方案类型" prop="cultureProgramType" class="narrow-input-item">
                      <el-select v-model="stateForm.cultureProgramType" placeholder="请选择" style="width: 100%" :disabled="isAuditMode">
                        <el-option v-for="dict in culture_program_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"/>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="8">
                    <el-form-item label="限制条件" prop="limitingCondition" class="narrow-input-item">
                      <el-input v-model="stateForm.limitingCondition" placeholder="请输入" :disabled="isAuditMode" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 第二部分：学分要求 -->
              <div class="form-section">
                <h4 class="section-subtitle">学分要求</h4>
                <el-row :gutter="24" class="form-grid mb-6">
                  <!-- 1. 总学分要求 + 右侧添加按钮 -->
                  <el-col :xs="24" :sm="24" :md="24" :lg="24">
                    <div class="total-credit-container">
                      <el-form-item label="总学分要求" prop="totalCredits" class="narrow-input-item wrap-label total-credit-item">
                        <el-input
                            v-model="stateForm.totalCredits"
                            placeholder="自动计算"
                            disabled
                            style="background-color: #f5f7fa; cursor: not-allowed;"
                        />
                      </el-form-item>
                      <el-button
                          type="primary"
                          icon="el-icon-plus"
                          @click="openCreditDialog"
                          class="add-credit-btn"
                          :disabled="isAuditMode"
                      >
                        添加学分类型
                      </el-button>
                    </div>
                  </el-col>

                  <!-- 2. 固定4类学分 -->
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <el-form-item label="专业必修课学分" prop="requiredCourseCredits" class="narrow-input-item wrap-label">
                      <el-input
                          v-model.number="stateForm.requiredCourseCredits"
                          placeholder="请输入"
                          type="number"
                          min="0"
                          step="1"
                          :disabled="isAuditMode"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <el-form-item label="公共必修课学分" prop="degreeCourseCredit" class="narrow-input-item wrap-label">
                      <el-input
                          v-model.number="stateForm.degreeCourseCredit"
                          placeholder="请输入"
                          type="number"
                          min="0"
                          step="1"
                          :disabled="isAuditMode"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <el-form-item label="专业选修课学分" prop="electiveCourseCredits" class="narrow-input-item wrap-label">
                      <el-input
                          v-model.number="stateForm.electiveCourseCredits"
                          placeholder="请输入"
                          type="number"
                          min="0"
                          step="1"
                          :disabled="isAuditMode"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="6" :lg="6">
                    <el-form-item label="实践环节学分" prop="practiceCredits" class="narrow-input-item wrap-label">
                      <el-input
                          v-model.number="stateForm.practiceCredits"
                          placeholder="请输入"
                          type="number"
                          min="0"
                          step="1"
                          :disabled="isAuditMode"
                      />
                    </el-form-item>
                  </el-col>

                  <!-- 3. 动态添加的学分类型 -->
                  <el-col
                      :xs="24"
                      :sm="12"
                      :md="6"
                      :lg="6"
                      v-for="(item, index) in selectedCreditTypes"
                      :key="item.key"
                  >
                    <el-form-item :label="`${item.label}学分`" :prop="item.key" class="narrow-input-item wrap-label">
                      <el-input
                          v-model.number="stateForm[item.key]"
                          placeholder="请输入"
                          type="number"
                          min="0"
                          step="1"
                          :disabled="isAuditMode"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>

              <!-- 附件上传 -->
              <el-row :gutter="16" class="upload-row">
                <el-col :xs="24">
                  <el-form-item label="附件上传" prop="attachmentUploadPath" class="upload-form-item">
                    <el-upload
                        class="upload-demo"
                        drag
                        :action="uploadAction"
                        :file-list="fileList"
                        :on-success="handleUploadSuccess"
                        :on-remove="handleFileRemove"
                        :before-upload="beforeUpload"
                        multiple
                        :disabled="isAuditMode"
                    >
                      <i class="el-icon-upload"></i>
                      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                      <div class="el-upload__tip" slot="tip">支持上传PDF、Word（doc/docx）、图片（jpg/png）文件，且不超过50MB</div>
                    </el-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：学分统计 + 课程管理 -->
    <el-row :gutter="20" class="mt-4">
      <!-- 左侧：学分统计 -->
      <el-col :md="6">
        <el-card>
          <div class="section-title">
            <h3>学分统计（已选/要求）</h3>
          </div>
          <div class="credit-stats">
            <!-- 1. 专业必修课 -->
            <div class="credit-item">
              <p class="credit-label">
                专业必修课：
                <span class="selected-credit">{{ computedMajorRequiredCredits }}</span>
                /
                <span class="required-credit">{{ stateForm.requiredCourseCredits || 0 }}</span>
                学分
                <span v-if="(stateForm.requiredCourseCredits || 0) > computedMajorRequiredCredits" class="lack-credit">
              （缺{{ (stateForm.requiredCourseCredits || 0) - computedMajorRequiredCredits }}分）
            </span>
              </p>
              <el-progress
                  v-if="stateForm.requiredCourseCredits > 0"
                  :percentage="Math.min((computedMajorRequiredCredits / stateForm.requiredCourseCredits) * 100, 100)"
                  stroke-width="6"
                  :color="computedMajorRequiredCredits >= (stateForm.requiredCourseCredits || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
            </div>
            <!-- 2. 公共必修课 -->
            <div class="credit-item">
              <p class="credit-label">
                公共必修课：
                <span class="selected-credit">{{ computedPublicRequiredCredits }}</span>
                /
                <span class="required-credit">{{ stateForm.degreeCourseCredit || 0 }}</span>
                学分
                <span v-if="(stateForm.degreeCourseCredit || 0) > computedPublicRequiredCredits" class="lack-credit">
              （缺{{ (stateForm.degreeCourseCredit || 0) - computedPublicRequiredCredits }}分）
            </span>
              </p>
              <el-progress
                  v-if="stateForm.degreeCourseCredit > 0"
                  :percentage="Math.min((computedPublicRequiredCredits / stateForm.degreeCourseCredit) * 100, 100)"
                  stroke-width="6"
                  :color="computedPublicRequiredCredits >= (stateForm.degreeCourseCredit || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
            </div>

            <!-- 3. 专业选修课 -->
            <div class="credit-item">
              <p class="credit-label">
                专业选修课：
                <span class="selected-credit">{{ computedMajorElectiveCredits }}</span>
                /
                <span class="required-credit">{{ stateForm.electiveCourseCredits || 0 }}</span>
                学分
                <span v-if="(stateForm.electiveCourseCredits || 0) > computedMajorElectiveCredits" class="lack-credit">
              （缺{{ (stateForm.electiveCourseCredits || 0) - computedMajorElectiveCredits }}分）
            </span>
              </p>
              <el-progress
                  v-if="stateForm.electiveCourseCredits > 0"
                  :percentage="Math.min((computedMajorElectiveCredits / stateForm.electiveCourseCredits) * 100, 100)"
                  stroke-width="6"
                  :color="computedMajorElectiveCredits >= (stateForm.electiveCourseCredits || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
            </div>

            <!-- 4. 实践环节 -->
            <div class="credit-item">
              <p class="credit-label">
                实践环节：
                <span class="selected-credit">{{ computedPracticeCredits }}</span>
                /
                <span class="required-credit">{{ stateForm.practiceCredits || 0 }}</span>
                学分
                <span v-if="(stateForm.practiceCredits || 0) > computedPracticeCredits" class="lack-credit">
              （缺{{ (stateForm.practiceCredits || 0) - computedPracticeCredits }}分）
            </span>
              </p>
              <el-progress
                  v-if="stateForm.practiceCredits > 0"
                  :percentage="Math.min((computedPracticeCredits / stateForm.practiceCredits) * 100, 100)"
                  stroke-width="6"
                  :color="computedPracticeCredits >= (stateForm.practiceCredits || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
            </div>

            <!-- 新增：动态学分类型统计项 -->
            <div
                class="credit-item"
                v-for="item in selectedCreditTypes"
                :key="item.key"
            >
              <p class="credit-label">
                {{ item.label }}：
                <span class="selected-credit">{{ computedDynamicCredits(item.key) }}</span>
                /
                <span class="required-credit">{{ stateForm[item.key] || 0 }}</span>
                学分
                <span
                    v-if="(stateForm[item.key] || 0) > computedDynamicCredits(item.key)"
                    class="lack-credit"
                >
              （缺{{ (stateForm[item.key] || 0) - computedDynamicCredits(item.key) }}分）
            </span>
              </p>
              <el-progress
                  v-if="stateForm[item.key] > 0"
                  :percentage="Math.min((computedDynamicCredits(item.key) / stateForm[item.key]) * 100, 100)"
                  stroke-width="6"
                  :color="computedDynamicCredits(item.key) >= (stateForm[item.key] || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
            </div>

            <!-- 5. 总学分 -->
            <div class="credit-item total-credit">
              <p class="credit-label">
                总学分：
                <span class="selected-credit">{{ totalCredits }}</span>
                /
                <span class="required-credit">{{ stateForm.totalCredits || 0 }}</span>
                学分
              </p>
              <el-progress
                  v-if="stateForm.totalCredits > 0"
                  :percentage="Math.min((totalCredits / stateForm.totalCredits) * 100, 100)"
                  stroke-width="6"
                  :color="totalCredits >= (stateForm.totalCredits || 0) ? '#67c23a' : '#409eff'"
                  class="credit-progress"
              />
              <p class="progress-text">
                {{ stateForm.totalCredits && totalCredits >= stateForm.totalCredits ? '总学分已满足要求' : '总学分未满足要求' }}
              </p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：课程管理 -->
      <el-col :md="18">
        <el-card>
          <div class="section-title">
            <h3>课程管理</h3>
          </div>
          <div class="course-section">
            <!-- 搜索区域 -->
            <el-row :gutter="18" class="mb-4">
              <el-col :xs="24">
                <div class="search-course-group" style="position: relative;">
                  <el-input
                      v-model="stateForm.courseSearch"
                      placeholder="输入课程名称/编号搜索（支持模糊匹配）"
                      @keyup.enter="searchCourses"
                      style="width: 400px"
                      :disabled="isAuditMode"
                  />
                  <el-button
                      type="primary"
                      @click="searchCourses"
                      :loading="searchLoading"
                      class="ml-4"
                      :disabled="isAuditMode"
                  >
                    搜索课程
                  </el-button>

                  <!-- 搜索结果 -->
                  <div v-if="searchCourseList.length > 0 && !isAuditMode" class="search-results">
                    <div
                        v-for="course in searchCourseList"
                        :key="course.id"
                        class="result-item"
                        @click="selectCourse(course)"
                    >
                      <span v-html="course.highlightName"></span>
                      <div class="meta">
                        编号：{{ course.courseCode }} | 学分：{{ course.credits || 0 }}
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>

            <!-- 已选课程表格 -->
            <el-row :gutter="16">
              <el-col :xs="24">
                <div class="selected-courses">
                  <el-table
                      :data="stateForm.courses"
                      border
                      max-height="450"
                      style="width: 100%; table-layout: fixed;"
                      stripe>
                    <el-table-column label="课程名称" prop="courseName" width="150" />
                    <el-table-column label="开课学院" prop="collegeId" width="80" />
                    <el-table-column label="学分" width="100">
                      <template #default="scope">
                        <el-input-number
                            v-model="scope.row.credits"
                            :min="0"
                            :max="100"
                            size="small"
                            controls-position="right"
                            style="width: 100%; padding: 0 8px;"
                            :disabled="isAuditMode"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="总学时" width="100">
                      <template #default="scope">
                        <el-input-number
                            v-model="scope.row.totalHours"
                            :min="0"
                            :max="1000"
                            size="small"
                            controls-position="right"
                            style="width: 100%; padding: 0 8px;"
                            :disabled="isAuditMode"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="年级" align="center" prop="grade"  width="80">
                      <template #default="scope">
                        <dict-tag :options="grade" :value="stateForm.grade"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="开课学期" width="110">
                      <template #default="scope">
                        <el-select
                            v-model="scope.row.courseSemester"
                            placeholder="请选择学期"
                            size="small"
                            style="width: 100%"
                            :disabled="isAuditMode"
                        >
                          <el-option
                              v-for="dict in semester"
                              :key="dict.value"
                              :label="dict.label"
                              :value="parseInt(dict.value)"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="授课方式" width="120">
                      <template #default="scope">
                        <el-select v-model="scope.row.teachingMethod" placeholder="请选择授课方式" size="small" :disabled="isAuditMode">
                          <el-option
                              v-for="dict in teaching_method"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="考试方式" width="120">
                      <template #default="scope">
                        <el-select v-model="scope.row.examMethod" placeholder="请选择考试方式" size="small" :disabled="isAuditMode">
                          <el-option
                              v-for="dict in method_examination"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="是否必修" width="90">
                      <template #default="scope">
                        <el-switch
                            v-model="scope.row.isRequired"
                            active-text="是"
                            inactive-text="否"
                            active-value="1"
                            inactive-value="0"
                            size="small"
                            :disabled="isAuditMode"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="课程性质" width="110">
                      <template #default="scope">
                        <el-select
                            v-model="scope.row.courseNature"
                            placeholder="请选择课程性质"
                            size="small"
                            :disabled="isAuditMode"
                            @change="() => handleCourseNatureChange(scope.row)"
                        >
                          <el-option
                              v-for="dict in characteristics_of_the_course"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                          />
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="90" v-if="!isAuditMode">
                      <template #default="scope">
                        <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            @click="removeCourse(scope.$index)"
                        >删除</el-button>
                      </template>
                    </el-table-column>
                    <template #empty>
                      <div class="empty-state-container">
                        <div class="empty-icon">
                          <i class="el-icon-search" style="font-size: 48px; color: #ccc;"></i>
                        </div>
                        <div class="empty-text" style="margin-top: 16px; color: #909399;">
                          暂无已选课程，请搜索并添加课程
                        </div>
                      </div>
                    </template>
                  </el-table>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <div class="form-actions mt-8">
      <el-button @click="handleBack" :disabled="isAuditMode">返回列表</el-button>

      <!-- 保存/修改按钮：状态为空或3时显示，审核模式不显示 -->
      <el-button
          :type="isEditMode ? 'success' : 'primary'"
          @click="submitForm"
          v-if="shouldShowSaveButton && !isAuditMode"
          :disabled="isAuditMode"
      >
        {{ isEditMode ? '修改培养方案' : '保存培养方案' }}
      </el-button>

      <!-- 新增：预览数据按钮 -->
      <el-button
          type="info"
          @click="previewFormData"
          v-if="shouldShowSaveButton && !isAuditMode"
      >
        预览提交数据
      </el-button>

      <!-- 审批通过按钮：状态为2且有审批权限时显示 -->
      <el-button
          type="success"
          icon="el-icon-check"
          @click="handleApprovePass"
          v-if="shouldShowApprovalButtons"
      >
        审批通过
      </el-button>

      <!-- 审批退回按钮：状态为2且有审批权限时显示 -->
      <el-button
          type="danger"
          icon="el-icon-close"
          @click="handleApproveReject"
          v-if="shouldShowApprovalButtons"
      >
        审批退回
      </el-button>
    </div>

    <!-- 新增：添加学分类型弹窗 -->
    <el-dialog
        title="添加/编辑学分类型"
        v-model="showCreditDialog"
        width="500px"
        :before-close="handleDialogClose"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :disabled="isAuditMode"
    >
      <div class="credit-type-selection">
        <el-checkbox-group v-model="checkedCreditTypes">
          <el-checkbox
              v-for="type in allCreditTypes"
              :key="type.key"
              :label="type.key"
              class="credit-type-item"
              :disabled="isAuditMode"
          >
            {{ type.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreditDialog = false" :disabled="isAuditMode">取消</el-button>
          <el-button type="primary" @click="confirmAddCreditTypes" :disabled="isAuditMode">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="TrainingManagementAdd">
import useUserStore from '@/store/modules/user';
import {ref, reactive, toRefs, onMounted, computed, getCurrentInstance, watchEffect} from 'vue';
import {useRouter, useRoute} from 'vue-router';
import {
  addTrainingProgramWithCourses,
  getTrainingManagement,
  updateProgramWithCourses,
  updateStatusById
} from "@/api/trainingManagement/trainingManagement";
import {listCourse,selectCourseList} from "@/api/course/course";
import {getMajorByCollegeId} from "@/api/major/major.js";
import {listFirstSubject, getFirstSubjectByCollegeId} from "@/api/college/firstSubject.js";
import {listSecondSubject, getSecondSubjectByCollegeId} from "@/api/college/secondSubject.js";
import {listResearchDirection, getResearchDirectionByCollegeId} from "@/api/college/researchDirection.js";
import {listCollege} from "@/api/college/college";
import { selectCollegeList } from "@/api/student/allList";
import {getProgramPoursesByTrainingId} from "@/api/trainingManagement/programPourses";
import {getCredit} from "@/api/trainingManagement/credit";
import {listTrainingManagementSubjectByTrainingProgramId} from "@/api/trainingManagement/trainingManagementSubject.js";
import {debounce} from 'lodash';
import {loadAllParams} from "@/api/page";
import {ElMessage} from 'element-plus';

const router = useRouter();
const route = useRoute();
const {proxy} = getCurrentInstance();
const isEditMode = ref(false);
const admissionType = ref('firstLevel');
// 添加审核模式标识
const isAuditMode = ref(route.query.isAudit === 'true');
const isFromTemplate = ref(!!route.query.fromTemplateId);
// 原始数据快照 - 关键新增
const originalData = ref(null);

// 学分弹窗相关状态
const showCreditDialog = ref(false);
const checkedCreditTypes = ref([]); // 弹窗中勾选的学分类型key
const selectedCreditTypes = ref([]); // 已选择并展示的学分类型（包含label和key）

// 学分类型映射表（包含字段索引和名称）
const CREDIT_MAPPING = {
  requiredCourseCredits: { fieldIndex: 1, dictKey: "1" },  // 专业必修课 → 字典键1
  degreeCourseCredit: { fieldIndex: 2, dictKey: "2" },     // 公共必修课 → 字典键2
  electiveCourseCredits: { fieldIndex: 3, dictKey: "3" },  // 专业选修课 → 字典键3
  practiceCredits: { fieldIndex: 4, dictKey: "4" },        // 实践环节 → 字典键4
  degreeBasicCredits: { fieldIndex: 5, dictKey: "5" },     // 学位基础课 → 字典键5
  academicExchangeCredits: { fieldIndex: 6, dictKey: "6" },// 学术交流环节 → 字典键6
  majorPracticeCredits: { fieldIndex: 7, dictKey: "7" },   // 专业实践课 → 字典键7
  thesisCredits: { fieldIndex: 8, dictKey: "8" },          // 学位论文 → 字典键8
  socialPracticeCredits: { fieldIndex: 9, dictKey: "9" }   // 社会实践 → 字典键9
};

// 所有可选学分类型（动态添加的类型）
const allCreditTypes = [
  {label: '学位基础课', key: 'degreeBasicCredits'},
  {label: '公共选修课', key: 'academicExchangeCredits'},
  {label: '学位专业课', key: 'majorPracticeCredits'},
  {label: '必修环节', key: 'thesisCredits'},
  {label: '补修环节', key: 'socialPracticeCredits'}
];

// 固定学分类型（必须存在的类型）
const fixedCreditTypes = [
  {label: '专业必修课', key: 'requiredCourseCredits'},
  {label: '公共必修课', key: 'degreeCourseCredit'},
  {label: '专业选修课', key: 'electiveCourseCredits'},
  {label: '实践环节', key: 'practiceCredits'}
];

// 上传相关状态
const uploadAction = ref("https://jsonplaceholder.typicode.com/posts/"); // 实际项目替换为真实上传接口
const fileList = ref([]);

// 字典数据
const {
  characteristics_of_the_course,
  semester,
  audit_status,
  culture_program_type,
  grade,
  teaching_method,
  method_examination
} =
    proxy.useDict('characteristics_of_the_course', 'semester', 'audit_status', 'culture_program_type', 'grade', 'teaching_method', 'method_examination');

// 学科相关数据
const firstLevelDisciplines = ref([]);
const allSecondLevelDisciplines = ref([]);
const allResearchDirections = ref([]);
const availableSecondLevels = ref([]);
const availableDirections = ref([]);
const trainingProgramSubjects = ref([]);
const allCourses = ref([]);
// 核心响应式数据
const state = reactive({
  form: {
    id: null,
    programCode: null,
    name: null,
    studentType: null,
    collegeId: null,
    collegeCode: null,
    englishName: null,
    totalCredits: 0,
    // 固定学分
    degreeCourseCredit: 0,      // 公共必修课
    requiredCourseCredits: 0,   // 专业必修课
    electiveCourseCredits: 0,   // 专业选修课
    practiceCredits: 0,         // 实践环节
    // 动态学分
    academicExchangeCredits: 0, // 学术交流环节
    degreeBasicCredits: 0,      // 学位基础课
    majorPracticeCredits: 0,    // 专业实践课
    thesisCredits: 0,           // 学位论文
    socialPracticeCredits: 0,   // 社会实践
    grade: null,
    cultureProgramType: null,
    attachmentUploadPath: null,
    limitingCondition: null,
    status: null,
    courses: [],                    // 已选课程列表
    courseSearch: '',               // 课程搜索关键词
    firstLevelDiscipline: null,
    secondLevelDiscipline: null,
    disciplineDirection: [],
    firstLevelCode: null,
    secondLevelCode: null,
    directionCodes: []
  },
  collegeList: [],
  filteredColleges: [],
  collegeLoading: false,
  searchCourseList: [],
  searchLoading: false,
  courseList: [],
  activeTab: 'program',
  currentStatus: null // 存储当前培养方案状态
});

const {
  form: stateForm,
  collegeList,
  filteredColleges,
  collegeLoading,
  searchCourseList,
  searchLoading,
  courseList,
  activeTab,
  currentStatus
} = toRefs(state);

// 1. 第一步：定义「学分统计的课程性质排序优先级」（与学分统计显示顺序完全一致）
// 顺序说明：专业必修课 → 公共必修课 → 专业选修课 → 实践环节 → 学位基础课 → 学术交流环节 → 专业实践课 → 学位论文 → 社会实践
const COURSE_NATURE_SORT_ORDER = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

// 2. 第二步：编写通用课程排序函数（核心逻辑）
const sortCourses = (courses) => {
  // 拆分：有课程性质的课程 + 无课程性质的课程
  const coursesWithNature = [...courses].filter(course =>
      course.courseNature !== '' && course.courseNature !== undefined && course.courseNature !== null
  );
  const coursesWithoutNature = [...courses].filter(course =>
      course.courseNature === '' || course.courseNature === undefined || course.courseNature === null
  );

  // 对「有性质的课程」按优先级排序（按 COURSE_NATURE_SORT_ORDER 的索引排序）
  const sortedWithNature = coursesWithNature.sort((a, b) => {
    // 统一转为字符串，避免数字/字符串类型差异导致排序错误
    const natureA = String(a.courseNature);
    const natureB = String(b.courseNature);
    // 取性质在排序数组中的索引，索引越小越靠前
    const indexA = COURSE_NATURE_SORT_ORDER.indexOf(natureA);
    const indexB = COURSE_NATURE_SORT_ORDER.indexOf(natureB);
    // 若某性质未在排序数组中（异常情况），默认放最后
    return (indexA === -1 ? 99 : indexA) - (indexB === -1 ? 99 : indexB);
  });

  // 拼接：有性质的课程在前，无性质的课程在后
  return [...sortedWithNature, ...coursesWithoutNature];
};

// 5. 第五步：在「修改课程性质」场景触发排序（实现 handleCourseNatureChange 方法）
const handleCourseNatureChange = (updatedCourse) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  // 找到修改后的课程，更新列表（确保数据同步）
  const courseIndex = stateForm.value.courses.findIndex(
      course => course.courseId === updatedCourse.courseId
  );
  if (courseIndex !== -1) {
    stateForm.value.courses[courseIndex] = { ...updatedCourse };
  }

  // 触发排序（更新列表顺序）
  stateForm.value.courses = sortCourses(stateForm.value.courses);
};

// 动态学分类型的课程性质映射
const DYNAMIC_CREDIT_NATURE_MAP = {
  degreeBasicCredits: "5",          // 学位基础课
  academicExchangeCredits: "6",    // 学术交流环节
  majorPracticeCredits: "7",       // 专业实践课
  thesisCredits: "8",              // 学位论文
  socialPracticeCredits: "9"      // 社会实践
};

// 计算动态学分类型的已选学分
const computedDynamicCredits = (creditKey) => {
  const natureCode = DYNAMIC_CREDIT_NATURE_MAP[creditKey];
  if (!natureCode) return 0;

  return stateForm.value.courses.reduce((sum, course) => {
    if (String(course.courseNature) === natureCode) {
      return sum + (Number(course.credits) || 0);
    }
    return sum;
  }, 0);
};

// 打开弹窗时回显已选中状态
const openCreditDialog = () => {
  checkedCreditTypes.value = selectedCreditTypes.value.map(item => item.key);
  showCreditDialog.value = true;
};
const ruleTrigger = ref(0);
// 确认添加/取消学分类型 - 修复核心：移除未选中类型的学分值
const confirmAddCreditTypes = () => {
  // 1. 找出被取消的学分类型
  const removedTypes = selectedCreditTypes.value
      .filter(type => !checkedCreditTypes.value.includes(type.key))
      .map(type => type.key);

  // 2. 将被取消的学分类型值重置为0
  removedTypes.forEach(key => {
    stateForm.value[key] = 0;
  });

  // 3. 根据勾选状态过滤
  const newSelectedTypes = allCreditTypes.filter(type =>
      checkedCreditTypes.value.includes(type.key)
  );

  // 4. 更新已选择列表
  selectedCreditTypes.value = newSelectedTypes;

  // 5. 手动触发规则刷新（关键修复：同步校验规则）
  ruleTrigger.value += 1;

  // 6. 关闭弹窗并清空勾选
  showCreditDialog.value = false;
  checkedCreditTypes.value = [];
};

// 关闭弹窗时清空勾选
const handleDialogClose = () => {
  checkedCreditTypes.value = [];
  showCreditDialog.value = false;
};

// 学分统计计算属性
const COURSE_NATURE_MAP = {
  MAJOR_REQUIRED: "1",     // 专业必修课
  PUBLIC_REQUIRED: "2",    // 公共必修课
  MAJOR_ELECTIVE: "3",     // 专业选修课
  PRACTICE: "4"            // 实践环节
};

const computedPublicRequiredCredits = computed(() => {
  return stateForm.value.courses.reduce((sum, course) => {
    if (String(course.courseNature) === COURSE_NATURE_MAP.PUBLIC_REQUIRED) {
      return sum + (Number(course.credits) || 0);
    }
    return sum;
  }, 0);
});

const computedMajorRequiredCredits = computed(() => {
  return stateForm.value.courses.reduce((sum, course) => {
    if (String(course.courseNature) === COURSE_NATURE_MAP.MAJOR_REQUIRED) {
      return sum + (Number(course.credits) || 0);
    }
    return sum;
  }, 0);
});

const computedMajorElectiveCredits = computed(() => {
  return stateForm.value.courses.reduce((sum, course) => {
    if (String(course.courseNature) === COURSE_NATURE_MAP.MAJOR_ELECTIVE) {
      return sum + (Number(course.credits) || 0);
    }
    return sum;
  }, 0);
});

const computedPracticeCredits = computed(() => {
  return stateForm.value.courses.reduce((sum, course) => {
    if (String(course.courseNature) === COURSE_NATURE_MAP.PRACTICE) {
      return sum + (Number(course.credits) || 0);
    }
    return sum;
  }, 0);
});

const totalCredits = computed(() =>
    stateForm.value.courses.reduce((sum, course) => sum + (Number(course.credits) || 0), 0)
);

// 表单验证规则
const crules = reactive({
  name: [{required: true, message: "方案名称不能为空", trigger: "blur"}],
  collegeId: [{required: true, message: "所属学院不能为空", trigger: "blur"}],
  grade: [{required: true, message: "年级不能为空", trigger: "blur"}],
  cultureProgramType: [{required: true, message: "培养方案类型不能为空", trigger: "blur"}],

  // 固定学分校验
  degreeCourseCredit: [
    {required: true, message: "公共必修课学分不能为空", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        // 先将值转换为数字
        const num = Number(value);
        if (isNaN(num)) {
          callback(new Error("请输入有效的数字"));
        } else if (num < 0) {
          callback(new Error("学分不能为负数"));
        } else if (!Number.isInteger(num)) {
          callback(new Error("学分必须为整数"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  requiredCourseCredits: [
    {required: true, message: "专业必修课学分不能为空", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) {
          callback(new Error("请输入有效的数字"));
        } else if (num < 0) {
          callback(new Error("学分不能为负数"));
        } else if (!Number.isInteger(num)) {
          callback(new Error("学分必须为整数"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  electiveCourseCredits: [
    {required: true, message: "专业选修课学分不能为空", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) {
          callback(new Error("请输入有效的数字"));
        } else if (num < 0) {
          callback(new Error("学分不能为负数"));
        } else if (!Number.isInteger(num)) {
          callback(new Error("学分必须为整数"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  practiceCredits: [
    {required: true, message: "实践环节学分不能为空", trigger: "blur"},
    {
      validator: (rule, value, callback) => {
        const num = Number(value);
        if (isNaN(num)) {
          callback(new Error("请输入有效的数字"));
        } else if (num < 0) {
          callback(new Error("学分不能为负数"));
        } else if (!Number.isInteger(num)) {
          callback(new Error("学分必须为整数"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  attachmentUploadPath: [{required: false, message: "请上传附件", trigger: "change"}],
  disciplineDirection: [
    {required: true, message: "请选择至少一个研究方向", trigger: "change"},
    {type: 'array', message: "请选择至少一个研究方向", trigger: "change"}
  ]
});

// 动态添加选中的动态学分校验规则
watchEffect(() => {
  // 依赖触发变量，确保选中项变化后重新计算规则
  ruleTrigger.value;

  // 先清除已有的动态学分验证规则
  selectedCreditTypes.value.forEach(item => {
    if (crules[item.key]) {
      delete crules[item.key];
    }
  });

  // 为当前选中的动态学分添加验证规则
  selectedCreditTypes.value.forEach(item => {
    crules[item.key] = [
      { required: true, message: `${item.label}学分不能为空`, trigger: "blur" },
      { type: 'number', message: "请输入有效的数字", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value < 0) callback(new Error("学分不能为负数"));
          else if (!Number.isInteger(value)) callback(new Error("学分必须为整数"));
          else callback();
        },
        trigger: "blur"
      }
    ];
  });
});

// 初始化表单数据逻辑（完整修改版）
const initFormFromOriginalData = () => {
  if (!originalData.value) return;

  const { program, courses, subjects, credits } = originalData.value;

  // 初始化培养方案主数据
  stateForm.value = { ...program };

  // 从模板新增时特殊处理：清除不需要回显的字段
  if (isFromTemplate.value) {
    // 清除学科及方向设置相关字段
    stateForm.value.collegeId = null;
    stateForm.value.collegeCode = null;
    stateForm.value.firstLevelDiscipline = null;
    stateForm.value.secondLevelDiscipline = null;
    stateForm.value.disciplineDirection = [];
    stateForm.value.firstLevelCode = null;
    stateForm.value.secondLevelCode = null;
    stateForm.value.directionCodes = [];

    // 清除方案编号
    stateForm.value.programCode = null;
  }

  // 初始化课程数据（保留原始id和关联关系）
  stateForm.value.courses = courses.map(linkedCourse => {
    const fullCourse = courseList.value.find(c => c.id === linkedCourse.courseId);
    return {
      id: linkedCourse.id, // 保留课程记录原始ID
      trainingProgramId: program.id, // 关联主表ID
      courseId: linkedCourse.courseId,
      credits: linkedCourse.credits,
      totalHours: linkedCourse.totalHours,
      courseSemester: linkedCourse.semester ? parseInt(linkedCourse.semester) : null,
      teachingMethod: linkedCourse.teachingMethod?.toString(),
      examMethod: linkedCourse.examMethod?.toString(),
      isRequired: linkedCourse.isRequired ? '1' : '0',
      courseNature: linkedCourse.courseCharacter?.toString(),
      courseName: fullCourse?.courseName || '未知课程',
      collegeId: fullCourse?.collegeId || '',
      courseCode: fullCourse?.courseCode || '未知编号',
      isCrossSemester: linkedCourse.isCrossSemester || 0, // 已有关联数据中的值，默认0
      crossSemesterCount: linkedCourse.crossSemesterCount || 1, // 已有关联数据中的值，默认0
      accomplishSemesterCount: linkedCourse.accomplishSemesterCount || 0 // 编辑时回显，默认0
    };
  });

  // 核心修复：优先从学分数据本身获取ID，其次关联主表的creditId
  // 解决提交时ID为空的问题
  stateForm.value.creditId = credits?.id || program.creditId || null;

  // 初始化学科方向数据
  trainingProgramSubjects.value = subjects.map(subj => ({ ...subj }));

  // 解析学分数据（从extendedField1-9）
  selectedCreditTypes.value = [];
  Object.entries(CREDIT_MAPPING).forEach(([creditKey, { fieldIndex }]) => {
    // 优先从学分数据取，其次从主数据取，确保数值类型
    const creditValue = credits
        ? Number(credits[`extendedField${fieldIndex}`] ?? 0)
        : Number(program[`extendedField${fieldIndex}`] ?? 0);
    stateForm.value[creditKey] = creditValue;

    // 处理动态学分类型选中状态
    if (allCreditTypes.some(t => t.key === creditKey) && creditValue > 0) {
      const creditType = allCreditTypes.find(t => t.key === creditKey);
      if (creditType && !selectedCreditTypes.value.includes(creditType)) {
        selectedCreditTypes.value.push(creditType);
      }
    }
  });

  // 处理附件
  if (stateForm.value.attachmentUploadPath) {
    fileList.value = [{
      name: stateForm.value.attachmentUploadPath.split('/').pop(),
      url: stateForm.value.attachmentUploadPath,
      status: 'success'
    }];
  }

  // 调试用：确认初始化后的学分ID（生产环境可删除）
  console.log('初始化的学分ID:', stateForm.value.creditId);
};
// 生命周期与数据加载
onMounted(async () => {
  // 审核模式下不加载编辑相关数据
  if (!isAuditMode.value) {
    await Promise.all([fetchCollegeList(), initCourseList()]);
    getCourseList();
  }

  const {id, fromTemplateId} = route.query;
  // 关键修复：如果同时存在id和fromTemplateId，以id为准（保存后状态）
  if (id) {
    isFromTemplate.value = false;  // 有明确id时强制关闭模板模式
    isEditMode.value = true;
    await loadTrainingData(id);
  } else if (fromTemplateId) {
    isFromTemplate.value = true;
    isEditMode.value = false;
    await loadTrainingData(fromTemplateId);
  }
});

const loadTrainingData = async (trainingId) => {
  try {
    proxy.$modal.loading("正在加载数据...");
    // 先获取培养方案主数据，因为需要从中获取degreeCourseCredit
    const trainingRes = await getTrainingManagement(trainingId);
    const trainingData = trainingRes.data;

    // 并行请求：关联课程 + 学科方向 + 学分信息（使用degreeCourseCredit作为参数）
    const [coursesRes, subjectRes, creditRes] = await Promise.all([
      getProgramPoursesByTrainingId(trainingId),
      listTrainingManagementSubjectByTrainingProgramId(trainingId),
      // 关键修改：使用degreeCourseCredit作为参数调用getCredit
      trainingData.degreeCourseCredit ? getCredit(trainingData.degreeCourseCredit) : Promise.resolve({data: {}})
    ]);

    // 提取并存储状态值
    state.currentStatus = isFromTemplate.value ? null : trainingData.status;
    // 处理研究方向为数组
    trainingData.disciplineDirection = Array.isArray(trainingData.disciplineDirection)
        ? trainingData.disciplineDirection
        : (trainingData.disciplineDirection ? [trainingData.disciplineDirection] : []);

    // 保存原始数据快照（包含学分信息）
    originalData.value = {
      program: JSON.parse(JSON.stringify(trainingData)),
      courses: JSON.parse(JSON.stringify(coursesRes.data?.rows || [])),
      subjects: JSON.parse(JSON.stringify(subjectRes.data || [])),
      credits: JSON.parse(JSON.stringify(creditRes.data || {})) // 保存学分数据
    };

    // 2. 基于原始数据初始化表单（供用户编辑的副本）
    initFormFromOriginalData();

    // 定义课程性质排序优先级（与学分统计顺序一致）
    const COURSE_NATURE_SORT_ORDER = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];

    // 对课程列表进行排序
    const sortCourses = (courses) => {
      // 拆分：有课程性质的课程 + 无课程性质的课程
      const coursesWithNature = [...courses].filter(course =>
          course.courseNature !== '' && course.courseNature !== undefined && course.courseNature !== null
      );
      const coursesWithoutNature = [...courses].filter(course =>
          course.courseNature === '' || course.courseNature === undefined || course.courseNature === null
      );

      // 对「有性质的课程」按优先级排序
      const sortedWithNature = coursesWithNature.sort((a, b) => {
        const natureA = String(a.courseNature);
        const natureB = String(b.courseNature);
        const indexA = COURSE_NATURE_SORT_ORDER.indexOf(natureA);
        const indexB = COURSE_NATURE_SORT_ORDER.indexOf(natureB);
        // 异常性质放最后
        return (indexA === -1 ? 99 : indexA) - (indexB === -1 ? 99 : indexB);
      });

      // 拼接：有性质的课程在前，无性质的课程在后
      return [...sortedWithNature, ...coursesWithoutNature];
    };

    // 执行排序并更新课程列表
    stateForm.value.courses = sortCourses(stateForm.value.courses);

    // 处理学科和研究方向
    if (stateForm.value.collegeId) {
      await handleCollegeChange(stateForm.value.collegeId);
      const firstSubject = trainingProgramSubjects.value[0];
      if (firstSubject) {
        admissionType.value = firstSubject.enrollmentType === 1 ? 'firstLevel' : 'secondLevel';
        const directionCodes = trainingProgramSubjects.value.map(item => item.rescarechDirectionId);

        if (admissionType.value === 'firstLevel') {
          const firstLevel = firstLevelDisciplines.value.find(
              item => item.firstSubjectCode === firstSubject.subjectId
          );
          if (firstLevel) {
            stateForm.value.firstLevelDiscipline = firstLevel.id;
            await handleFirstLevelChange(firstLevel.id);
            const validDirIds = directionCodes.map(code => {
              const dir = availableDirections.value.find(d => d.researchDirectionCode === code);
              return dir ? dir.id : null;
            }).filter(Boolean);
            stateForm.value.disciplineDirection = validDirIds;
          }
        } else {
          const secondLevel = allSecondLevelDisciplines.value.find(
              item => item.secondSubjectCode === firstSubject.subjectId
          );
          if (secondLevel) {
            const firstLevel = firstLevelDisciplines.value.find(
                item => item.firstSubjectCode === secondLevel.firstSubjectId
            );
            if (firstLevel) {
              stateForm.value.firstLevelDiscipline = firstLevel.id;
              await handleFirstLevelChange(firstLevel.id);
              stateForm.value.secondLevelDiscipline = secondLevel.id;
              await handleSecondLevelChange(secondLevel.id);
              const validDirIds = directionCodes.map(code => {
                const dir = availableDirections.value.find(d => d.researchDirectionCode === code);
                return dir ? dir.id : null;
              }).filter(Boolean);
              stateForm.value.disciplineDirection = validDirIds;
            }
          }
        }
      }
    }

    proxy.$modal.closeLoading();
  } catch (error) {
    proxy.$modal.closeLoading();
    console.error('加载失败:', error);
    proxy.$modal.msgError('加载数据失败，请重试');
  }
};


const fetchCollegeList = async () => {
  collegeLoading.value = true;
  try {
    const res = await selectCollegeList();
    //const res = await listCollege({pageSize: 1000});
    collegeList.value = res.rows || [];
    filteredColleges.value = [...collegeList.value];
  } catch (e) {
    console.error('学院列表加载失败:', e);
    proxy.$modal.msgError('学院列表加载失败');
  } finally {
    collegeLoading.value = false;
  }
};

const initCourseList = async () => {
  try {
    proxy.$modal.loading("正在加载课程数据...");
    // 调用无参接口获取全量课程
    const res = await selectCourseList();

    // 添加详细的调试信息
    console.log('课程接口返回完整数据:', res);

    // 检查返回数据结构是否符合预期
    if (!res || !Array.isArray(res.rows)) {
      throw new Error('课程数据格式不正确，期望rows数组');
    }

    // 保存全量课程到本地
    allCourses.value = res.rows || [];
    // 同时给课程列表赋值（不影响原有功能）
    courseList.value = allCourses.value;
    console.log('已加载全量课程，共', allCourses.value.length, '条');

    // 显示成功消息
    proxy.$modal.msgSuccess(`已加载 ${allCourses.value.length} 门课程`);
  } catch (error) {
    console.error('课程列表加载失败:', error);
    proxy.$modal.msgError(`课程列表加载失败: ${error.message}`);
  } finally {
    proxy.$modal.closeLoading();
  }
};

// 学科联动与课程管理
const handleCollegeChange = async (selectedCollegeId) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  firstLevelDisciplines.value = [];
  allSecondLevelDisciplines.value = [];
  allResearchDirections.value = [];
  availableSecondLevels.value = [];
  availableDirections.value = [];
  stateForm.value.firstLevelDiscipline = null;
  stateForm.value.secondLevelDiscipline = null;
  stateForm.value.disciplineDirection = [];

  if (!selectedCollegeId) return;

  try {
    const college = collegeList.value.find(c => c.collegeId === selectedCollegeId);
    if (!college) {
      proxy.$modal.msgWarning("未找到对应学院");
      return;
    }
    stateForm.value.collegeCode = college.collegeCode;

    const [firstSubRes, secondSubRes, dirRes] = await Promise.all([
      getFirstSubjectByCollegeId(college.collegeCode),
      getSecondSubjectByCollegeId(college.collegeCode),
      getResearchDirectionByCollegeId(college.collegeCode)
    ]);
    firstLevelDisciplines.value = firstSubRes.data || [];
    allSecondLevelDisciplines.value = secondSubRes.data || [];
    allResearchDirections.value = dirRes.data || [];
  } catch (error) {
    console.error('学科数据加载失败:', error);
    proxy.$modal.msgError('获取学科数据失败');
  }
};

const handleFirstLevelChange = (firstLevelId) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  stateForm.value.secondLevelDiscipline = null;
  stateForm.value.disciplineDirection = [];
  availableSecondLevels.value = [];
  availableDirections.value = [];

  if (!firstLevelId) return;
  const firstLevel = firstLevelDisciplines.value.find(item => item.id === firstLevelId);
  if (!firstLevel) return;

  stateForm.value.firstLevelCode = firstLevel.firstSubjectCode;
  if (admissionType.value === 'firstLevel') {
    availableDirections.value = allResearchDirections.value.filter(
        item => item.secondSubjectId === firstLevel.firstSubjectCode
    );
  } else {
    availableSecondLevels.value = allSecondLevelDisciplines.value.filter(
        item => item.firstSubjectId === firstLevel.firstSubjectCode
    );
  }
};

const handleSecondLevelChange = (secondLevelId) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  stateForm.value.disciplineDirection = [];
  availableDirections.value = [];

  if (!secondLevelId) return;
  const secondLevel = allSecondLevelDisciplines.value.find(item => item.id === secondLevelId);
  if (!secondLevel) return;

  stateForm.value.secondLevelCode = secondLevel.secondSubjectCode;
  availableDirections.value = allResearchDirections.value.filter(
      item => item.secondSubjectId === secondLevel.secondSubjectCode
  );
};

const setAdmissionType = (type) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  admissionType.value = type;
  stateForm.value.firstLevelDiscipline = null;
  stateForm.value.secondLevelDiscipline = null;
  stateForm.value.disciplineDirection = [];
  availableSecondLevels.value = [];
  availableDirections.value = [];
};

const searchCourses = () => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  const keyword = stateForm.value.courseSearch?.trim();
  if (!keyword) {
    proxy.$modal.msgWarning("请输入课程名称或编号");
    searchCourseList.value = [];
    return;
  }

  // 本地模糊搜索（不调用接口）
  searchLoading.value = true;

  // 延迟模拟加载效果（可选，提升用户体验）
  setTimeout(() => {
    try {
      // 核心：前端过滤逻辑，匹配课程名称或编号
      const filtered = allCourses.value.filter(course => {
        // 转为小写忽略大小写
        const lowerKeyword = keyword.toLowerCase();
        // 匹配课程名称或课程编号（根据实际字段调整）
        const matchName = course.courseName?.toLowerCase().includes(lowerKeyword);
        const matchCode = course.courseCode?.toLowerCase().includes(lowerKeyword);
        return matchName || matchCode;
      });

      // 处理高亮显示
      searchCourseList.value = filtered.map(course => ({
        ...course,
        highlightName: highlightCourseName(course, keyword)
      }));
    } catch (e) {
      console.error('本地搜索失败:', e);
      proxy.$modal.msgError('搜索处理失败');
    } finally {
      searchLoading.value = false;
    }
  }, 200); // 模拟网络延迟，可根据需要调整
};

const highlightCourseName = (course, keyword) => {
  const courseName = course.courseName || '未知课程';
  return courseName.replace(
      new RegExp(`(${keyword})`, 'gi'),
      '<span style="color: #409eff; font-weight: 500;">$1</span>'
  );
};

const selectCourse = (course) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  if (stateForm.value.courses.some(c => c.courseId === course.id)) {
    proxy.$modal.msgWarning('该课程已添加');
    return;
  }

  // 新增课程（原逻辑不变）
  const newCourse = {
    courseId: course.id,
    courseName: course.courseName,
    collegeId: course.collegeId,
    courseCode: course.courseCode,
    credits: course.credits || 0,
    totalHours: course.totalHours || 0,
    courseType: course.courseType,
    courseNature: course.courseNature || '',  // 初始可能无性质
    courseSemester: course.semester || null,
    isCrossSemester: course.isCrossSemester || 0,
    crossSemesterCount: course.crossSemesterCount || 1
  };
  stateForm.value.courses.push(newCourse);

  // 新增：添加课程后触发排序
  stateForm.value.courses = sortCourses(stateForm.value.courses);

  // 原逻辑：清空搜索
  stateForm.value.courseSearch = '';
  searchCourseList.value = [];
};

const removeCourse = (index) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  proxy.$modal.confirm('确认删除该课程？').then(() => {
    stateForm.value.courses.splice(index, 1);
    proxy.$modal.msgSuccess('课程已删除');
  });
};

const getCourseList = () => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  //listCourse(loadAllParams).then(res => {
  selectCourseList(loadAllParams).then(res => {
    courseList.value = res.rows || [];
  }).catch(err => console.error('获取课程列表失败:', err));
};

// 新增：预览提交数据方法
const previewFormData = () => {
  try {
    const missingFields = checkFormCompleteness();
    if (missingFields.length > 0) {
      proxy.$modal.msgWarning(`以下必填项未填写：\n${missingFields.join('、')}`);
      return;
    }

    const programData = processProgramData();
    const creditData = processCreditData();
    const coursesData = processCoursesData();
    const directionCodes = getSelectedDirectionCodes();
    const disciplinesData = processDisciplinesData(directionCodes);

    const payload = {
      program: programData,
      credit: creditData,
      courses: coursesData,
      disciplinesData
    };

    // 显示预览弹窗
    proxy.$modal({
      title: '提交数据预览',
      content: `<pre style="max-height: 500px; overflow-y: auto; font-size: 12px;">${JSON.stringify(payload, null, 2)}</pre>`,
      html: true,
      cancelText: '关闭',
      confirmText: '确认提交',
      onConfirm: () => {
        // 直接提交表单
        submitForm();
      }
    });
  } catch (err) {
    proxy.$modal.msgError(`预览数据失败：${err.message}`);
    console.error('预览错误:', err);
  }
};

// 上传方法
const handleUploadSuccess = (response, uploadFile, uploadFiles) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  const fileUrl = `https://example.com/files/${uploadFile.name}`;
  stateForm.value.attachmentUploadPath = fileUrl;
  fileList.value = uploadFiles;
  ElMessage.success('文件上传成功');
};

const handleFileRemove = (_, uploadFiles) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  stateForm.value.attachmentUploadPath = null;
  fileList.value = uploadFiles;
  ElMessage.info('文件已移除');
};

const beforeUpload = (file) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return false;

  const supportTypes = [
    'image/jpeg', 'image/png',
    'application/pdf',
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  ];
  const isSupport = supportTypes.includes(file.type);
  const isLt50MB = file.size < 50 * 1024 * 1024;

  if (!isSupport) ElMessage.error('仅支持PDF、Word、图片格式');
  if (!isLt50MB) ElMessage.error('文件大小不能超过50MB');
  return isSupport && isLt50MB;
};

// 提交与返回
// 处理基本信息方法
const processProgramData = () => {
  // 创建一个新对象，避免直接修改源数据
  const programData = JSON.parse(JSON.stringify(stateForm.value));

  // 移除不需要的字段，但保留总学分（已从移除列表中排除totalCredits）
  const fieldsToRemove = [
    ...Object.keys(CREDIT_MAPPING),  // 所有学分相关字段（不包含totalCredits）
    'courses', 'courseSearch',
    'collegeCode', 'disciplineDirection'
  ];

  // 移除扩展字段1-10，因为这些会通过credit对象传递
  for (let i = 1; i <= 10; i++) {
    fieldsToRemove.push(`extendedField${i}`);
    fieldsToRemove.push(`extendedField${i}Name`);
  }

  // 执行移除操作
  fieldsToRemove.forEach(key => {
    delete programData[key];
  });

  // 确保必须的基础字段存在
  if (!programData.createBy) {
    programData.createBy = userStore.user?.username || '';
  }

  // 编辑模式下保留更新时间
  if (isEditMode.value && !programData.updateTime) {
    // 生成后端要求的 "yyyy-MM-dd HH:mm:ss" 格式
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    programData.updateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  // 确保总学分字段存在（即使值为0也保留）
  if (programData.totalCredits === undefined || programData.totalCredits === null) {
    programData.totalCredits = 0;
  }

  return programData;
};


// 全量检查表单数据完整性
const checkFormCompleteness = () => {
  const missingFields = [];

  // 检查基础信息
  if (!stateForm.value.name) missingFields.push('方案名称');
  if (!stateForm.value.collegeId) missingFields.push('所属学院');
  if (stateForm.value.grade === null) missingFields.push('年级');
  if (stateForm.value.cultureProgramType === null) missingFields.push('培养方案类型');

  // 检查学分要求
  if (stateForm.value.degreeCourseCredit === null) missingFields.push('公共必修课学分');
  if (stateForm.value.requiredCourseCredits === null) missingFields.push('专业必修课学分');
  if (stateForm.value.electiveCourseCredits === null) missingFields.push('专业选修课学分');
  if (stateForm.value.practiceCredits === null) missingFields.push('实践环节学分');

  // 检查动态学分
  selectedCreditTypes.value.forEach(item => {
    if (stateForm.value[item.key] === null) {
      missingFields.push(`${item.label}学分`);
    }
  });

  // 检查学科方向
  if (!stateForm.value.disciplineDirection || stateForm.value.disciplineDirection.length === 0) {
    missingFields.push('研究方向');
  }

  return missingFields;
};

// 处理学分数据提交逻辑（完整修改版）
const processCreditData = () => {
  const programId = stateForm.value.id; // 获取当前培养方案ID
  // 初始化学分数据结构
  const creditData = {
    id: stateForm.value.creditId || null, // 关键修复：确保传递初始化时保存的学分ID
    programId: programId, // 关联当前培养方案ID
    totalCredits: stateForm.value.totalCredits || 0
  };

  // 处理所有学分类型，生成extendedFieldX和extendedFieldXName
  Object.entries(CREDIT_MAPPING).forEach(([creditKey, { fieldIndex, dictKey }]) => {
    const fieldName = `extendedField${fieldIndex}`;
    const fieldNameProp = `${fieldName}Name`;

    // 确保数值类型正确，避免字符串导致的后端解析问题
    creditData[fieldName] = Number(stateForm.value[creditKey] ?? 0);
    creditData[fieldNameProp] = dictKey;  // 保存字典键而非显示名称
  });

  // 显式处理未使用的字段，保持与后端数据结构一致
  creditData.extendedField10 = null;
  creditData.extendedField10Name = null;

  // 调试用：确认ID是否正确传递（生产环境可删除）
  console.log('提交的学分ID:', creditData.id);

  return creditData;
};


// 3. 修改学分统计显示用的映射关系（用于前端显示正确名称）
const CREDIT_DISPLAY_NAMES = {
  "1": "专业必修课",
  "2": "公共必修课",
  "3": "专业选修课",
  "4": "实践环节",
  "5": "学位基础课",
  "6": "学术交流环节",
  "7": "专业实践课",
  "8": "学位论文",
  "9": "社会实践"
};

// 处理课程数据方法
const processCoursesData = () => {
  const programId = stateForm.value.id; // 获取当前培养方案ID
  return stateForm.value.courses.map(course => ({
    id: course.id || null, // 传递已有课程的id（编辑时需要）
    trainingProgramId: programId, // 关联当前培养方案ID
    courseId: course.courseId,
    courseCharacter: course.courseNature ? parseInt(course.courseNature) : null,
    credits: Number(course.credits) || 0,
    totalHours: Number(course.totalHours) || 0,
    teachingMethod: course.teachingMethod ? parseInt(course.teachingMethod) : null,
    examMethod: course.examMethod ? parseInt(course.examMethod) : null,
    isRequired: parseInt(course.isRequired) || 0,
    grade: parseInt(stateForm.value.grade) || null,
    semester: course.courseSemester ? parseInt(course.courseSemester) : null,
    status: 1,
    isCrossSemester: parseInt(course.isCrossSemester) || 0, // 转Integer类型，默认0
    crossSemesterCount: parseInt(course.crossSemesterCount) || 1, // 转Long类型，默认0
    accomplishSemesterCount: 0 // 固定传0，符合需求
  })).filter(c => c.courseId);
};


// 处理研究方向数据方法
const processDisciplinesData = (directionCodes) => {
  const programId = stateForm.value.id;
  return directionCodes.map((code, index) => ({
    id: trainingProgramSubjects.value[index]?.id || null, // 传递已有方向的id（编辑时需要）
    trainingProgramId: programId, // 已包含，确保不变
    enrollmentType: admissionType.value === 'firstLevel' ? 1 : 2,
    subjectId: admissionType.value === 'firstLevel'
        ? stateForm.value.firstLevelCode
        : stateForm.value.secondLevelCode,
    rescarechDirectionId: code
  }));
};

const submitForm = () => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  // 获取表单引用并进行验证
  const disciplineForm = proxy.$refs["disciplineFormRef"];
  const creditForm = proxy.$refs["creditFormRef"];
  if (!disciplineForm || !creditForm) {
    proxy.$modal.msgError("表单引用不存在");
    return;
  }

  // 同时校验两个表单，收集错误信息
  Promise.all([
    new Promise((resolve) => {
      disciplineForm.validate((valid, errFields) => {
        if (!valid) console.log("学科表单校验失败：", errFields);
        resolve(valid);
      });
    }),
    new Promise((resolve) => {
      creditForm.validate((valid, errFields) => {
        if (!valid) {
          console.log("学分表单校验失败：", errFields);
          // 修复核心：错误信息属性是message而非errMsg，且处理可能的空值
          const errMsg = Object.values(errFields)
              .flatMap(fields => fields) // 处理嵌套数组结构
              .map(f => {
                // 确保字段名和错误信息存在，避免undefined
                const fieldName = f.field || '未知字段';
                const errorMessage = f.message || '校验失败';
                return `${fieldName}：${errorMessage}`;
              })
              .join("；");
          proxy.$modal.msgWarning(`学分校验失败：${errMsg}`);
        }
        resolve(valid);
      });
    })
  ]).then(([disValid, creditValid]) => {
    const isAllValid = disValid && creditValid;
    if (!isAllValid) {
      proxy.$modal.msgWarning("表单校验未通过，请检查必填项");
      // 滚动到第一个错误字段
      const errorDom = document.querySelector(".el-form-item__error");
      if (errorDom) errorDom.scrollIntoView({ behavior: "smooth" });
      return;
    }

    // 验证课程列表不为空
    if (stateForm.value.courses.length === 0) {
      proxy.$modal.msgWarning("请至少添加一门课程");
      return;
    }

    // 验证学分要求是否满足
    if (totalCredits.value < stateForm.value.totalCredits) {
      if (!confirm(`总学分未满足要求(${totalCredits.value}/${stateForm.value.totalCredits})，是否继续提交？`)) {
        return;
      }
    }

    try {
      // 处理各部分数据
      const programData = processProgramData();
      const creditData = processCreditData();
      const coursesData = processCoursesData();
      const directionCodes = getSelectedDirectionCodes();

      if (directionCodes.length === 0) {
        proxy.$modal.msgWarning("请选择研究方向");
        return;
      }

      const disciplinesData = processDisciplinesData(directionCodes);

      // 构建完整的提交数据
      const payload = {
        program: programData,
        credit: creditData,
        courses: coursesData,
        disciplinesData
      };

      // 编辑模式下必须包含ID
      if (isEditMode.value) {
        payload.program.id = stateForm.value.id;
        payload.program.status = 2;
        if (!payload.program.id) {
          proxy.$modal.msgError("培养方案ID不存在，无法更新");
          return;
        }
      } else {
        // 新增时设置初始状态
        programData.status = 2;
      }

      // 提交数据
      proxy.$modal.loading(isEditMode.value ? "正在更新..." : "正在保存...");

      const submitPromise = isEditMode.value
          ? updateProgramWithCourses(payload)
          : addTrainingProgramWithCourses(payload);

      submitPromise
          .then(response => {
            proxy.$modal.closeLoading();
            const successMsg = isEditMode.value
                ? "更新培养方案及关联数据成功"
                : "新增培养方案及关联数据成功";
            proxy.$modal.msgSuccess(successMsg);

            // 新增成功后切换到编辑模式
            if (!isEditMode.value) {
              stateForm.value.id = response.data.id;
              isEditMode.value = true;
              isFromTemplate.value = false;
              // 关键修复：更新路由参数，移除fromTemplateId
              router.push({
                path: router.currentRoute.value.path,
                query: {
                  ...router.currentRoute.value.query,
                  id: response.data.id,
                  fromTemplateId: undefined  // 清除模板参数
                }
              });
              // 重新加载数据，更新原始快照
              loadTrainingData(stateForm.value.id);
            } else {
              // 编辑成功后刷新数据，更新原始快照
              loadTrainingData(stateForm.value.id);
            }
          })
          .catch(error => {
            proxy.$modal.closeLoading();
            const errorMsg = error?.response?.data?.msg ||
                (isEditMode.value ? "更新失败" : "保存失败");
            proxy.$modal.msgError(`操作失败：${errorMsg}`);
            console.error('提交失败:', error);
          });
    } catch (err) {
      proxy.$modal.closeLoading();
      proxy.$modal.msgError(`处理数据时发生错误：${err.message}`);
      console.error('数据处理错误:', err);
    }
  });
};

const getSelectedDirectionCodes = () => {
  return stateForm.value.disciplineDirection.map(dirId => {
    const dir = allResearchDirections.value.find(d => d.id === dirId);
    return dir ? dir.researchDirectionCode : null;
  }).filter(Boolean);
};

const handleUpdateSubmit = async (payload) => {
  try {
    proxy.$modal.loading("正在更新...");
    await updateProgramWithCourses(payload);
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("修改成功");
  } catch (error) {
    proxy.$modal.closeLoading();
    const msg = error?.response?.data?.msg || '修改失败';
    proxy.$modal.msgError(`修改失败：${msg}`);
  }
};

const handleAddSubmit = async (payload) => {
  try {
    proxy.$modal.loading("正在保存...");
    const res = await addTrainingProgramWithCourses(payload);
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("保存成功");
    stateForm.value.id = res.data.id;
    isEditMode.value = true;
  } catch (error) {
    proxy.$modal.closeLoading();
    const msg = error?.response?.data?.msg || '保存失败';
    proxy.$modal.msgError(`保存失败：${msg}`);
  }
};

const handleBack = () => {
  router.push('/trainingManagement');
};

// 自动计算总学分 - 修复核心：只计算选中的学分类型
watchEffect(() => {
  // 获取所有固定学分类型的key
  const fixedCreditKeys = fixedCreditTypes.map(credit => credit.key);

  // 获取当前选中的动态学分类型的key
  const selectedDynamicCreditKeys = selectedCreditTypes.value.map(item => item.key);

  // 合并需要计算的学分类型key
  const allCreditKeysToCalculate = [...fixedCreditKeys, ...selectedDynamicCreditKeys];

  // 计算总学分
  const total = allCreditKeysToCalculate.reduce((sum, key) => {
    return sum + Number(stateForm.value[key] || 0);
  }, 0);

  stateForm.value.totalCredits = total;
});

const filterColleges = debounce((query) => {
  // 审核模式下不执行任何操作
  if (isAuditMode.value) return;

  collegeLoading.value = true;
  if (query) {
    const q = query.toLowerCase();
    filteredColleges.value = collegeList.value.filter(c =>
        c.collegeName.toLowerCase().includes(q) || c.collegeCode.includes(query)
    );
  } else {
    filteredColleges.value = [...collegeList.value];
  }
  collegeLoading.value = false;
}, 300);

const userStore = useUserStore();
console.log('用户信息（userStore.roles）：', userStore.roles);

// 判断用户是否有审批按钮显示权限（角色为 GraduateOffice 或 admin）
const hasApprovalPermission = computed(() => {
  // 获取用户角色列表，默认空数组防止报错
  const userRoles = userStore.roles || [];
  // 判断是否包含指定角色（忽略大小写，确保兼容性）
  return userRoles.some(role =>
      ['GraduateOffice', 'admin'].includes(role)
  );
});

// 审批通过/退回方法
const handleApprovePass = () => {
  // 审批通过逻辑
  proxy.$modal.confirm('确定要审批通过该培养方案吗？')
      .then(async () => {
        try {
          // 调用状态更新接口，传入培养方案ID和状态1（审批通过）
          await updateStatusById(stateForm.value.id, 1);
          proxy.$modal.msgSuccess('审批通过成功');
          // 刷新当前页面数据
          await loadTrainingData(stateForm.value.id);
        } catch (error) {
          const msg = error?.response?.data?.msg || '审批操作失败';
          proxy.$modal.msgError(`审批失败：${msg}`);
          // 失败时也刷新页面确保状态同步
          await loadTrainingData(stateForm.value.id);
        }
      })
      .catch(() => {});
};

const handleApproveReject = () => {
  proxy.$modal.confirm('确定要审批退回该培养方案吗？')
      .then(async () => {
        try {
          // 调用状态更新接口，传入培养方案ID和状态1（审批通过）
          await updateStatusById(stateForm.value.id, 3);
          proxy.$modal.msgSuccess('审批退回成功');
          // 刷新当前页面数据
          await loadTrainingData(stateForm.value.id);
        } catch (error) {
          const msg = error?.response?.data?.msg || '审批操作失败';
          proxy.$modal.msgError(`审批失败：${msg}`);
          // 失败时也刷新页面确保状态同步
          await loadTrainingData(stateForm.value.id);
        }
      })
      .catch(() => {});
};

// 获取当前培养方案状态的方法
const getCurrentProgramStatus = () => {
  // 直接返回存储的状态值
  return state.currentStatus;
};

// 根据状态判断是否显示保存/修改按钮
const shouldShowSaveButton = computed(() => {
  const status = getCurrentProgramStatus();
  // 状态为空或者3时显示保存/修改按钮
  return status === null || status === 3;
});

// 根据状态和权限判断是否显示审批按钮
const shouldShowApprovalButtons = computed(() => {
  const status = getCurrentProgramStatus();
  // 状态为2且有审批权限时显示审批按钮
  return status === 2 && hasApprovalPermission.value;
});
</script>


<style scoped>
/* 全局样式 */
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.el-row {
  width: 100%;
}

.el-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  background: #fff;
}

/* 面包屑与标题 */
.page-header {
  margin-bottom: 20px;
}

.section-title {
  margin: 16px 0;
  padding-left: 8px;
  border-left: 4px solid #409eff;
}

.section-title h3 {
  margin: 0;
  font-size: 16px;
  color: #1f2329;
  font-weight: 500;
}

/* 基础信息/学分要求区域标题样式（视觉区分） */
.form-section {
  margin-bottom: 24px;
}

.section-subtitle {
  font-size: 14px;
  color: #409eff;
  margin-bottom: 12px;
  padding-bottom: 4px;
  border-bottom: 1px solid #e4e7ed;
  font-weight: 500;
}

/* 统一表单样式：确保各部分对齐 */
.uniform-form {
  width: 100%;
  padding: 0 16px;
}

.uniform-row {
  width: 100%;
  margin: 0 !important;
}

.uniform-form-item {
  margin-bottom: 16px !important;
  width: 100%;
}

.uniform-form-item :deep(.el-form-item__label) {
  width: 100px !important;
  text-align: left !important;
  padding-right: 10px !important;
  font-size: 14px !important;
}

.uniform-form-item :deep(.el-form-item__content) {
  width: calc(100% - 110px) !important;
}

.uniform-button-container {
  width: 100%;
  margin-bottom: 16px;
  padding: 0 !important;
}

.uniform-button-form-item {
  margin-bottom: 0 !important;
}

.uniform-button-form-item :deep(.el-form-item__label) {
  width: 100px !important;
  visibility: hidden;
}

.uniform-button-form-item :deep(.el-form-item__label)::after {
  content: "招生类型";
  visibility: visible;
  display: inline-block;
}

.uniform-button-form-item :deep(.el-form-item__content) {
  width: calc(100% - 110px) !important;
  padding-left: 0 !important;
  margin-left: 0 !important;
}

.discipline-buttons {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
  margin: 0 !important;
  padding: 0 !important;
}

/* 总学分与添加按钮布局 */
.total-credit-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  gap: 16px;
}

.total-credit-item {
  flex: 1;
  margin-bottom: 0 !important;
}

.add-credit-btn {
  white-space: nowrap;
  min-width: 120px;
}

/* 学分类型弹窗样式 */
.credit-type-selection {
  padding: 10px 0;
}

.credit-type-item {
  display: block;
  margin-bottom: 12px;
  cursor: pointer;
}

.credit-type-item :deep(.el-checkbox__label) {
  font-size: 14px;
  color: #303133;
}

/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 16px !important;
}

.narrow-input-item :deep(.el-input),
.narrow-input-item :deep(.el-select) {
  max-width: 200px !important;
}

.wrap-label :deep(.el-form-item__label) {
  white-space: normal !important;
  line-height: 1.5;
}

/* 上传组件 */
.upload-row {
  margin-top: 8px;
}

.upload-form-item :deep(.el-form-item__content) {
  width: calc(100% - 120px) !important;
}

:deep(.el-upload--drag) {
  border: 2px dashed #dcdfe6 !important;
  border-radius: 6px !important;
  padding: 40px 0 !important;
}

:deep(.el-upload__text) {
  font-size: 14px !important;
  color: #606266 !important;
}

:deep(.el-upload__tip) {
  font-size: 12px !important;
  color: #909399 !important;
  margin-top: 8px !important;
}

/* 课程搜索与表格 */
.search-course-group {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
  position: relative;
}

.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  width: 400px;
  z-index: 9999;
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  padding: 8px;
  margin-top: 4px;
}

.result-item {
  padding: 8px 12px;
  cursor: pointer;
  transition: background 0.3s;
}

.result-item:hover {
  background: #f5f7fa;
}

.result-item .meta {
  font-size: 12px;
  color: #8492a6;
  margin-top: 4px;
}

.selected-courses {
  margin-top: 16px;
  border-top: 1px dashed #e4e7ed;
  padding-top: 16px;
}

:deep(.el-table__header th) {
  background: #69c0ff !important;
  color: #fff !important;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

/* 学分统计样式 */
.credit-stats {
  padding: 20px;
  line-height: 1.8;
}

.credit-item {
  margin-bottom: 16px;
}

.credit-label {
  font-size: 14px;
  color: #303133;
  margin-bottom: 8px;
  display: block;
}

.selected-credit {
  color: #409eff;
  font-weight: 500;
}

.required-credit {
  color: #303133;
  font-weight: 500;
}

.lack-credit {
  color: #f56c6c;
  font-size: 12px;
  margin-left: 8px;
}

.credit-progress {
  width: 100%;
  margin-top: 4px;
  margin-bottom: 8px;
}

.total-credit {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px dashed #e4e7ed;
}

.progress-text {
  text-align: center;
  color: #67c23a;
  margin-top: 8px;
  font-size: 14px;
}

/* 响应式适配 */
@media (max-width: 1024px) {
  .form-grid .el-col:deep([class*="md-8"]) {
    flex: 0 0 50% !important;
    max-width: 50% !important;
  }

  .form-grid .el-col:deep([class*="md-12"]),
  .form-grid .el-col:deep([class*="md-6"]) {
    flex: 0 0 100% !important;
    max-width: 100% !important;
  }

  .total-credit-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .add-credit-btn {
    margin-left: 0;
    margin-top: 8px;
  }
}

@media (max-width: 768px) {
  .uniform-form-item :deep(.el-form-item__label),
  .uniform-button-form-item :deep(.el-form-item__label) {
    width: 80px !important;
  }

  .uniform-form-item :deep(.el-form-item__content),
  .uniform-button-form-item :deep(.el-form-item__content) {
    width: calc(100% - 90px) !important;
  }

  .discipline-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .search-course-group :deep(.el-input) {
    width: 100% !important;
  }

  .search-results {
    width: 100% !important;
  }

  :deep(.el-upload--drag) {
    padding: 20px 0 !important;
  }

  .narrow-input-item :deep(.el-input),
  .narrow-input-item :deep(.el-select) {
    max-width: 100% !important;
  }
}

@media (max-width: 480px) {
  .upload-form-item :deep(.el-form-item__content) {
    width: 100% !important;
  }

  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto !important;
  }
}

/* 操作按钮 */
.form-actions {
  margin-top: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 16px 0;
}
</style>
